package com.vanke.devops.domain;

import com.vanke.devops.domain.domain.users.IUsersService;
import com.vanke.devops.domain.domain.users.dto.UsersDTO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 权限检查类
 *
 * @author 李剑洪
 * @version 2016年5月20日 下午3:44:45
 */
@Component
public class UserRealm extends AuthorizingRealm {

	private final Logger logger = LoggerFactory.getLogger(UserRealm.class);

	@Autowired
	private IUsersService usersService;

	// 权限
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return new SimpleAuthorizationInfo();
	}

	// 登录验证
	@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

		UsersDTO usersDTO = usersService.getByLoginName(token.getUsername());
		StringBuilder sb = new StringBuilder(100);
		for (int i = 0; i < token.getPassword().length; i++) {
			sb.append(token.getPassword()[i]);
		}
		if(usersDTO.getPassword().equalsIgnoreCase(sb.toString())){
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(usersDTO.getId(),
					usersDTO.getPassword(),usersDTO.getUsername());
			super.clearCachedAuthorizationInfo(authcInfo.getPrincipals());
			return authcInfo;
		}
		return null;
	}
}
